/**
 * 
 */
package ganggaroo.kbs.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;

import ganggaroo.kbs.service.TwitDefaultVO;
import ganggaroo.kbs.service.TwitInfoVO;
import ganggaroo.kbs.service.TwitService;

/**
 * @author ganggaroo
 *
 */
public class TwitServiceImpl implements TwitService {

	protected Log log = LogFactory.getLog(this.getClass());
	
	/**
	 * 연관된 트윗을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 VO
	 * @return List<TwitInfoVO>
	 * @exception Exception
	 */
	public List<TwitInfoVO> selectTwitList(TwitDefaultVO searchVO) throws Exception {
		// TODO Auto-generated method stub
		String keyWord = searchVO.getSearchKeyword();
		
		Twitter twitter = new TwitterFactory().getInstance();
		Query query = new Query(keyWord);
		QueryResult result = twitter.search(query);
		
		return matchVO(result.getTweets());
	}
	
	/**
	 * 트윗 과 TwitInfoVO 동기화 한다.
	 * @param searchVO - 조회할 정보가 담긴 VO
	 * @return List<TwitInfoVO>
	 * @exception Exception
	 */
	private List<TwitInfoVO> matchVO(List<Tweet> tweets) throws Exception {
		
		List<TwitInfoVO> twitList = new ArrayList<TwitInfoVO>();
		for (Tweet tweet : tweets) {
			TwitInfoVO twitInfo = new TwitInfoVO();
			
			twitInfo.setFromUser(tweet.getFromUser());
			twitInfo.setToUser(tweet.getToUser());
			twitInfo.setIsoLanguageCode(tweet.getIsoLanguageCode());
			twitInfo.setLocation(tweet.getLocation());
			twitInfo.setProfileImageUrl(tweet.getProfileImageUrl());
			twitInfo.setSource(tweet.getSource());
			twitInfo.setText(tweet.getText());
			twitInfo.setCreatedAt(tweet.getCreatedAt());
			
			log.debug("tweet info ::: " + twitInfo.toString());
			twitList.add(twitInfo);
		}
		
		return twitList;
	}

}
